<?php

namespace App\Kuafu\Complain\Service;


use App\Exceptions\BaseException;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Complain\Jobs\ComplainSubmitJob;
use App\Kuafu\Complain\Model\ComplainModel;
use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Service\UserService;
use App\Library\FeiShu\SendFs;
use App\Library\KfHttp\TigerCurl;
use App\Remote\Rms\RmsUserRemote;
use App\Scope\ShopScope;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

class ComplainService extends BaseService
{

    /**
     * 新增投诉
     * @param $request
     * @param $shopId
     * @param $userId
     * @throws BaseException
     */
    public static function addComplain($request, $shopId, $userId)
    {
        try {
            $shopInfo = ShopService::getShopInfo($shopId);
            if (!$shopInfo) {
                throw new ShopException(ShopCodeEnum::ERR_SHOP_ID_NO_EXIST);
            }
//            $orderSerialNum = '0';
//            $field          = ['shopId', 'orderId', 'serialNum', 'createdAt'];
//            $orderInfo      = OrderService::getOrderFieldByOrderId($request->orderId, $field, $shopId);
//            if ($orderInfo) {
//                $orderSerialNum = str_pad($orderInfo['serialNum'], CodeEnum::ORDER_LEADING_ZERO, "0", STR_PAD_LEFT);
//            }
            $imgData = [];
            foreach ($request->img as $v) {
                $imgData[] = str_replace(config('other.IMAGE_URL') . 'applet-images/', '', $v);
            }
            $insertData = [
                "shopId"         => $shopId,
                "userId"         => $userId,
                "orderId"        => $request->orderId ?? 0,
                "problemPid"     => $request->problemPid,
                "problemChildId" => $request->problemChildId,
                "reason"         => $request->reason,
                "desc"           => $request->desc,
                "phone"          => $request->phone,
                "img"            => json_encode($imgData),
            ];
            $data       = ComplainModel::addComplain($insertData);

            // todo 异步处理飞书消息通知
            dispatch((new ComplainSubmitJob($data->id)))->onQueue(ComplainSubmitJob::$QUEUE_NAME);
//            $shopName   = $shopInfo['shopCode'] . $shopInfo['name'];
            //推送飞书群消息
            /*机器人消息 ：
            标题：小程序订单投诉通知
            门店编号
            订单编号
            投诉原因
            补充描述
            联系电话
            消息@颜路、扶苏、露西*/
//            $content   = <<<STR
//门店名称: {$shopName}
//订单编号: {$request->orderId}
//订单流水: {$orderSerialNum}
//联系电话: {$request->phone}
//投诉原因: {$request->reason}
//补充描述: {$request->desc}
//
//STR;
//            $noticeUrl = CommonService::getComplainInfoWenAppUrl($data->id);//跳转到对应后台详情
//            $title     = "小程序订单投诉通知" . '(' . $shopInfo['shopCode'] . '-' . $request->reason . ')';
//            $atUids = config('other.FS_APPLET_COMPLAIN_AT_USER_ID');
//            if ($atUids) {
//                $atUids = explode(',',$atUids);
//            }
//            SendFs::newRobot(SendFs::ROBOT_APPLET_COMPLAIN)
//                ->setTitleContent($title, $content)
//                ->setAtAll()
//                ->setUrl('查看详情', $noticeUrl, 1)
//                ->send();

            //给用户发短信
            //出餐问题、菜品问题、承诺未履行反馈
            //亲爱的顾客您好，很抱歉给您带来不愉快的用餐体验，夸父炸串已收到您的投诉，并在联系门店处理中，请保持电话畅通，门店将会尽快致电您沟通解决事宜，如遇用餐高峰请耐心等待。
            $templateCode = config('sms.ali.appletComplainOneCodeTemplate');
            if ($request->problemPid == 3) {//config表 key=complainIssueList
                //客服未回复反馈
                //亲爱的顾客您好，已经收到您关于“客服未回复”的投诉，已联系客服为您尽快解决问题，请您耐心等待。
                $templateCode = config('sms.ali.appletComplainTwoCodeTemplate');
            }
            if(config('app.env') == 'prod'){
                SmsService::getClient()->send($request->phone, $templateCode, []);
            }
        } catch (\Exception $exception) {
            handleException($exception, "解除绑定失败");
        }
    }

    /**
     * 获取配置的描述问题
     * @return mixed
     */
    public static function getIssueList(): array
    {
        $data = ConfigModel::getConfigByTypeKey('appletComplain', 'complainIssueList');
        $list = json_decode($data[0]['value'], true);
        return $list ?? [];
    }

    public static function ComplainLists($status, $orderNo, $submitTimeStart, $submitTimeEnd, $completeTimeStart, $completeTimeEnd, $problemPid, $problemChildId, $pageSize, $pageNum, $export): array
    {
        $paginator = ComplainModel::query()
            ->when(
                $status != "", function ($query) use ($status) {
                $query->where('status', $status);
            }
            )
            ->when(
                $orderNo, function ($query) use ($orderNo) {
                $query->where('orderId', (int)$orderNo);
            }
            )
            ->when(
                $problemPid, function ($query) use ($problemPid) {
                $query->where('problemPid', $problemPid);
            }
            )
            ->when(
                $problemChildId, function ($query) use ($problemChildId) {
                $query->where('problemChildId', $problemChildId);
            }
            )
            ->when(
                $submitTimeStart,
                function ($query) use ($submitTimeStart) {
                    $query->where("createdAt", ">=", strtotime($submitTimeStart));
                }
            )
            ->when(
                $submitTimeEnd,
                function ($query) use ($submitTimeEnd) {
                    $query->where("createdAt", "<", strtotime($submitTimeEnd) + 86400);
                }
            )
            ->when(
                $completeTimeStart,
                function ($query) use ($completeTimeStart) {
                    $query->where("completeTime", ">=", strtotime($completeTimeStart));
                }
            )
            ->when(
                $completeTimeEnd,
                function ($query) use ($completeTimeEnd) {
                    $query->where("completeTime", "<", strtotime($completeTimeEnd) + 86400);
                }
            )
            ->when(
                ShopScope::getShopIdsArr(), function ($query) {
                $query->whereIn("shopId", ShopScope::getShopIdsArr());
            }
            )
            ->with(
                ['shopRel', 'userRel']
            )
            ->select(['id', 'orderId', 'shopId', 'reason', 'status', 'completeTime', 'createdAt', 'updatedByUid', 'desc', 'remark'])
            ->orderByDesc('createdAt')
            ->orderByDesc('completeTime')
            ->when(
                $export,
                function ($query) {
                    return $query->get();
                },
                function ($query) use ($pageNum, $pageSize) {
                    return $query->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                }
            );

        $list = $paginator->map(
            function (ComplainModel $complainModel) {
                return [
                    'id'           => $complainModel->id,
                    'orderId'      => (string)$complainModel->orderId,
                    'shopId'       => $complainModel->shopId,
                    'shopCode'     => optional($complainModel->shopRel)->shopCode,
                    'shopName'     => optional($complainModel->shopRel)->name,
                    'reason'       => $complainModel->reason,
                    'desc'         => $complainModel->desc,
                    'remark'       => $complainModel->remark,
                    'completeTime' => (string)formatDate($complainModel->completeTime),
                    'createdAt'    => (string)formatDate(strtotime($complainModel->createdAt)),
                    'status'       => $complainModel->status,
                    'updatedByUid' => $complainModel->updatedByUid,
                    'managerNames' => (string)optional($complainModel->userRel)->username,
                ];
            }
        );
        if ($export) {
            self::exportComplainLists($list);
        }
        return [
            'lists'     => $list,
            'count'     => $paginator->total(),
            'pageSize'  => $pageSize,
            'pageNum'   => $pageNum,
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
        ];
    }

    public static function exportComplainLists($list)
    {
        ini_set('max_execution_time', 100000);
        header("Content-Disposition: attachment; filename=" . urlencode('小程序投诉工单') . date('Y-m-d') . '.csv');

        // UTF8的BOM头
        $fd = fopen('php://output', 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        fputcsv(
            $fd, [
                '提交时间',
                '门店编号',
                '订单编号',
                '投诉原因一级',
                '投诉原因二级',
                '处理时间',
                '状态',
                '处理人',
                '补充描述',
                '客服备注',
            ]
        );
        $list->each(
            function ($item) use (&$fd) {
                $reason = explode(' - ', $item['reason']);
                fputcsv(
                    $fd, [
                        $item['createdAt'],
                        $item['shopCode'] . $item['shopName'],
                        is_numeric($item['orderId']) ? ("'" . $item['orderId']) : $item['orderId'],
                        $reason[0] ?? '',
                        $reason[1] ?? '',
                        $item['completeTime'],
                        ComplainModel::MAPPING_STATUS[$item['status']],
                        $item['managerNames'],
                        $item['desc'],
                        $item['remark'],
                    ]
                );
                ob_flush();
                flush();
            }
        );

        fputcsv($fd, []);

        if (is_resource($fd)) {
            fclose($fd);
        }
        die;
    }

    /**
     * get info
     * @param $request
     * @return array
     * @throws GuzzleException
     */
    public static function getComplainInfo($request): array
    {
        $info = ComplainModel::getComplainInfoById($request->id);
        if ($info) {
            $info     = $info->toArray();
            $imgArray = json_decode($info['img']);
            $imgData  = [];
            foreach ($imgArray as $v) {
                if (!str_contains($v, "http")) {
                    $imgData[] = config('other.IMAGE_URL') . 'applet-images/' . $v;
                } else {
                    $imgData[] = $v;
                }
            }
            $info['img']           = $imgData;
            $info['completeTime']  = formatDate($info['completeTime']);
            $info['orderId']       = (string)$info['orderId'];
            $info['managerNames']  = $info['user_rel'] ? $info['user_rel']['username'] : "";
            $userIds               = $info['shop_rel'] ? $info['shop_rel']['councilorId'] : 0;
            $getManagerByTigerData = TigerCurl::getIns()
                    ->do(
                        'internal/shop/getOrganizationInfo', ['type' => 2, 'provinceCode' => $info['shop_rel'] ? $info['shop_rel']['province'] : 0],
                        'GET'
                    )['data'] ?? [];
            if ($getManagerByTigerData) {
                $userIds = $userIds . ',' . $getManagerByTigerData['operationUid'];
            }
            $userInfo = collect($userIds ? UserService::getUserInfoByIds($userIds, ['id', 'mobile', 'username']) : [])->pluck(null, "id");

            $info['shopInfo'] = [
                'shopCode'              => $info['shop_rel'] ? $info['shop_rel']['shopCode'] : "",
                'shopName'              => $info['shop_rel'] ? $info['shop_rel']['name'] : "",
                'mobile'                => $info['shop_rel'] ? $info['shop_rel']['shopMobile'] : "",
                'addressPrefix'         => $info['shop_rel'] ? $info['shop_rel']['addressPrefix'] : "",
                'address'               => $info['shop_rel'] ? $info['shop_rel']['address'] : "",
                'branch'                => $info['shop_rel'] ? $info['shop_rel']['branch'] : "",
                'provincialTotal'       => $getManagerByTigerData["operationName"] ?? "",//省总
                'provincialTotalMobile' => $userInfo->get($getManagerByTigerData["operationUid"] ?? 0)["mobile"] ?? "",
                'supervisor'            => $userInfo->get($info['shop_rel'] ? $info['shop_rel']['councilorId'] : 0)["username"] ?? "",//督导
                'supervisorMobile'      => $userInfo->get($info['shop_rel'] ? $info['shop_rel']['councilorId'] : 0)["mobile"] ?? "",
            ];
            unset($info['user_rel'], $info['shop_rel']);
            return $info;
        }
        return [];
    }


    /**
     * 修改小程序-投诉工单
     * @param $request
     * @param $userId
     * @return mixed|void
     */
    public static function updateComplain($request, $userId)
    {
        $data = ['status' => ComplainModel::STATUS_SUC, 'updatedByUid' => $userId, 'completeTime' => time()];
        if ($request['remark']) {
            $data['remark'] = $request['remark'];
        }
        ComplainModel::setComplainInfoById($request->id, $data);
    }
}
